#!/usr/bin/env python
#
# Copyright 2012 GEOFBOT
#
# Licensed under the GNU Public License version 3
#
import cgi
import datetime
import urllib
import webapp2
import os
#import time

#from google.appengine.ext import db
from google.appengine.api import users
'''
class CSVsub(db.Model):
    author = db.StringProperty()
    csv = db.StringProperty(multiline=True)
    date = db.DateTimeProperty(auto_now_add=True)

def guestbook_key(guestbook_name=None):
    return db.Key.from_path('Guestbook', guestbook_name or 'default_guestbook')'''

class MainHandler(webapp2.RequestHandler):
    def get(self):
        allowedNames = []
        with open(os.path.join(os.path.split(__file__)[0], 'data', 'allowedusers.txt')) as au:
            for line in au:
                line = line.partition('#')[0]
                if line:
                    allowedNames.append(line.rstrip())
                                
        user = users.get_current_user()
        #guestbook_name=self.request.get('guestbook_name')

        #posts = db.GqlQuery("SELECT * "
        #                        "FROM Post "
        #                        "WHERE ANCESTOR IS :1 ",
        #                        guestbook_key(guestbook_name))
        allowedNames=list(set(allowedNames)) # Remove dupes

        if user:
            if str(user.email()).partition('@')[0] in allowedNames:
                self.response.write("""
<html>
    <p><b>Hello</b>, %s<br />
    <a href="%s">Click here to logout.</a></p>""" % (user.nickname(),users.create_logout_url(self.request.uri)))
                
                self.response.write("""<p><h1>Submit a CSV</h1></p>
                                    <p><form action="/sign" method="post">
                                    <div>Name:<br />
                                    <input type="text" name="name"></div>
                                    <div>Paste CSV here:<br />
                                    <textarea name="content" rows="3" cols="60"></textarea></div>
                                    <div><input type="submit" value="Submit CSV"></div></form></html></p>""")
            else:
                self.response.write("""
                                    <html>
                                      <p><b>Hello</b>, %s<br />
                                      Sorry, you do not have permission to access this application.  <a href="%s">Click here to logout.</a></p>""" % (user.nickname(),users.create_logout_url(self.request.uri)))
                                    

        else:
            self.response.write("""
              <html>
                <p><b>Hello</b>, guest.<br /><a href=\"%s\">Sign in or register here.</a></p>
              </html>""" % users.create_login_url(self.request.uri))

        #for post in posts:
        #    if post.author:
        #        self.response.write(
        #            '<b>%s</b> wrote:' % post.author)
        #    else:
        #        self.response.write('An anonymous visitor wrote:')
        #    self.response.write('<blockquote>%s</blockquote>' % cgi.escape(post.content))

class Guestbook(webapp2.RequestHandler):
    def post(self):
#        guestbook_name = self.request.get('guestbook_name')
#        csv = CSVsub(parent=guestbook_key(guestbook_name))

 #       if users.get_current_user():
 #           post.author = users.get_current_user().nickname()

#        post.csv = self.request.get('content')
#        post.put()
        self.response.write("""<html>
                            <head><meta http-equiv="refresh" content="3;url=/"></head>
                            <body>You submitted a CSV with title <tt>%s</tt> and with the following contents:
                            <pre>""" % cgi.escape(self.request.get('name')))
        self.response.write(cgi.escape(self.request.get('content')))
        self.response.write('</pre></body></html>')
#        time.sleep(3)
#        self.redirect('/')
        
app = webapp2.WSGIApplication([
    ('/', MainHandler),
    ('/sign', Guestbook)
], debug=True)
